package com.sservice.web.controller.admin;

import com.sservice.common.CompareObject;
import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.model.vo.GoodsPriceIndexVo;
import com.sservice.model.vo.GoodsVo;
import com.sservice.urp.entity.Role;
import com.sservice.urp.entity.User;
import com.sservice.urp.vo.UserVo;
import com.sservice.service.service.IGoodsPriceIndexService;
import com.sservice.service.service.IGoodsService;
import com.sservice.service.service.IOfferService;
import com.sservice.service.service.ISysLogService;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.model.entity.*;
import com.sservice.web.log.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/goods")
public class GoodsController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IGoodsService depService;
    @Autowired
    private IOfferService offerService;
    @Autowired
    private IGoodsPriceIndexService gpiService;
    @Autowired
    private ISysLogService sysLogService;


    /**
     * 创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Integer> create(Goods arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        User user = (User) session.getAttribute(Constants.USER);
        arg.setCreatorId(String.valueOf(user.getId()));
        arg.setCreator(user.getUserName());
        int service_res = depService.insertSelective(arg);
        if (service_res > 0) {
            sysLogService.log("创建", request, Integer.valueOf(arg.getId()), Action.goodsType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * 价格指数
     *
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public BaseResult<Map> index(GoodsPriceIndexVo arg, HttpSession session) {
        List<GoodsPriceIndex> list = gpiService.queryByPageAndGoodsId(arg);
        Goods goods = depService.selectByPrimaryKey(Integer.valueOf(arg.getGoodsId()));
        Map map = new HashMap();
        map.put("goods", goods);
        map.put("prices", list);
        BaseResult<Map> res = new BaseResult(true, map);
        return res;
    }

    /**
     * @param arg
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Goods arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Offer of = new Offer();
        of.setGoodsId(String.valueOf(arg.getId()));
        int count = offerService.queryCountByGoodsId(of);
        BaseResult<Object> res = null;
        if (count > 0) {
            res = new BaseResult(false, "该产品已关联报价数据,不能删除!", 403);
        } else {
            int service_res = depService.deleteByPrimaryKey(arg.getId());
            if (service_res > 0) {
                sysLogService.log("删除", request, Integer.valueOf(arg.getId()), Action.goodsType);
            }
            res = new BaseResult(true, service_res);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Goods> get(Goods arg) {
        Goods service_res = depService.selectByPrimaryKey(arg.getId());
        BaseResult<Goods> res = new BaseResult<Goods>(true, service_res);
        return res;
    }

    /**
     * @param arg
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Object> update(Goods arg, String operator_, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Goods goods = depService.selectByPrimaryKey(arg.getId());
        if (arg.getOperatorId() != null) {
            Goods g = depService.selectByPrimaryKey(arg.getId());
            String[] gstr = g.getOperatorId().split(",");
            boolean flag = false;
            String name = "";
            for (int t = 0; t < gstr.length; t++) {
                if (("," + arg.getOperatorId() + ",").indexOf("," + gstr[t] + ",") == -1) {
                    Offer of = new Offer();
                    of.setCreatorId(gstr[t]);
                    of.setGoodsId(String.valueOf(arg.getId())); //当前产品的运营人员
                    Integer res = offerService.queryCountMyOfferByCreatorId(of);
                    if (res > 0) {
                        flag = true;
                        name = g.getOperator().split(",")[t];
                        break;
                    }
                }
            }
            if (flag) {
                return new BaseResult(false, "用户" + name + "已经发布报价数据，不能从运营中删除!", 403);
            }
        }
        int service_res = depService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {
            Map<String, Object> res = CompareObject.contrastObj(arg, goods);
            if (operator_ != null) {
                res.put("operatorId", "变更为" + operator_);
            }
            sysLogService.log(res, request, Integer.valueOf(arg.getId()), Action.goodsType);
        }
        BaseResult res = new BaseResult(true, service_res);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(GoodsVo arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        if (user == null) {
            return new ListResult(false, "未登录!", 401);
        }

        Boolean isManger = false;
        for (Role role : user.getRoles()) {
            if (String.valueOf(role.getId()).equals(Constants.SUPER_MANAGER_ROLE_ID)) { /// 超级管理员账户判断
                isManger = true;
            }
        }
        if (!isManger) { //运营账户判断
            GoodsVo goods = new GoodsVo();
            List<Goods> list = depService.queryGoodsCategory(goods);
            List<String> lstr = new ArrayList<String>();
            for (Goods item : list) {
                if (("," + item.getOperatorId() + ",").indexOf("," + user.getId() + ",") > -1) {
                    lstr.add(String.valueOf(item.getId()));
                }
            }
            if (lstr.size() > 0) {
                arg.setList(lstr);
            }
        }
        if (!isManger && null == arg.getList()) {
            return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
        }
        List<Goods> list = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryData", method = RequestMethod.GET)
    public ListResult queryData(GoodsVo arg, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        if (user == null) {
            return new ListResult(false, "未登录!", 401);
        }
        List<Goods> list = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }
}
